package com.buercc.boot.intercept;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ApiInterceptor implements HandlerInterceptor {

    //请求之前
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {


        HttpSession sessoin = httpServletRequest.getSession();

        System.out.println(sessoin.getAttribute("xxxx"));

        String sessionId = sessoin.getId();
        Cookie cookie = new Cookie("JSESSIONID", sessionId);
        Cookie cookie_user = new Cookie("user_info", "sahdbxhaxkjsajk");

        sessoin.setAttribute("user_id", "xxxxx");
        cookie.setPath(httpServletRequest.getContextPath());
        cookie_user.setPath(httpServletRequest.getContextPath());



        cookie.setMaxAge(2 * 60);// 30 分钟
        // 设置cookis

        httpServletResponse.addCookie(cookie_user);
        httpServletResponse.addCookie(cookie);

        System.out.println("进入拦截器");
        return true;
    }

    //请求时
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    //请求完成
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("推出拦截器");
    }
}
